package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink03_Transform_FlatMap {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
//        DataStreamSource<String> streamSource = env.readTextFile("input/word.txt");

        //TODO 3.使用Flatmap将读取过来的数据切出一个个单词
        SingleOutputStreamOperator<String> result = streamSource.flatMap(new MyFlatMap());

        result.print();

        env.execute();
    }

    //使用flatMap富函数
    public static class MyFlatMap extends RichFlatMapFunction<String,String>{
        /**
         * 生命周期方法 open最先被调用 每个并行度上调用一次  适合做一些初始化工作 比如创建链接
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open...");
        }

        /**
         * 生命周期方法 close最后被调用 每个并行度上调用一次 适合做一些清理工作 比如关闭链接释放资源
         * 在1.13.0版本及以前，在读文件的时候，一个并行度调用两次close方法
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close...");
        }

        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {

            //getRuntimeContext可以获取到更多信息 还可以初始化状态
            System.out.println(getRuntimeContext().getTaskName());
            String[] words = value.split(" ");

            for (String word : words) {
                out.collect(word);
            }
        }

    }
}
